package xyz.xtt.admin.service.impl;

import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.toolkit.JoinWrappers;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import xyz.xtt.admin.constants.ErrorMessage;
import xyz.xtt.admin.entity.*;
import xyz.xtt.admin.exception.ChainException;
import xyz.xtt.admin.mapper.AssetAccountMapper;
import xyz.xtt.admin.mapper.AssetTransactionRecordMapper;
import xyz.xtt.admin.request.AssetAccountRecordReqest;
import xyz.xtt.admin.request.AssetAccountRequest;
import xyz.xtt.admin.service.IAssetAccountService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import xyz.xtt.admin.service.IUserService;
import xyz.xtt.admin.utils.MyAESUtil;
import xyz.xtt.admin.utils.ToolsUtil;
import xyz.xtt.admin.vo.AssetAccountVo;
import xyz.xtt.admin.vo.AssetTransationRecordVo;

import java.util.Objects;

/**
 * <p>
 * 资产帐户表 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-01-17
 */
@Service
public class AssetAccountServiceImpl extends ServiceImpl<AssetAccountMapper, TblAssetAccount> implements IAssetAccountService {

    @Autowired
    private IUserService userService;
    @Autowired
    private AssetTransactionRecordMapper assetTransactionRecordMapper;
    @Autowired
    private AssetAccountMapper assetAccountMapper;

    public Page<AssetAccountVo> getList( AssetAccountRequest req) {
        MPJLambdaWrapper<TblAssetAccount> query = JoinWrappers.lambda(TblAssetAccount.class)
                .selectAll(TblAssetAccount.class)
                .select(TblAsset::getAssetName)
                .select(TblUser::getNickname, TblUser::getPhone)
                .leftJoin(TblAsset.class, TblAsset::getId, TblAssetAccount::getAssetId)
                .leftJoin(TblUser.class, TblUser::getAppUserId, TblAssetAccount::getOwnerId);

        // 根据用户名称 或者手机号 获取数据
        if(StringUtils.isNotBlank(req.getName()) || StringUtils.isNotBlank(req.getPhone())) {
            try {
              TblUser user =  userService.getUserByNameAndPhone(req.getName(), req.getPhone());
              if (Objects.isNull(user)) {
                  return null;
              }
              query.eq(TblAssetAccount::getOwnerId, user.getAppUserId());
            }catch (Exception e){
                throw new ChainException(ErrorMessage.ARGUMENT_NOT_VALID);
            }
        }
        if(StringUtils.isNotBlank(req.getStartTime())) {
            try {
                Long start = ToolsUtil.parseDate(req.getStartTime());
                query.gt(TblAssetAccount::getCreateTime, start);
            } catch (Exception e) {
                throw new ChainException(ErrorMessage.ARGUMENT_NOT_VALID);
            }
        }
        if(StringUtils.isNotBlank(req.getEndTime())) {
            try {
                Long end = ToolsUtil.parseDate(req.getEndTime());
                query.lt(TblAssetAccount::getCreateTime, end);
            } catch (Exception  e) {
                throw new ChainException(ErrorMessage.ARGUMENT_NOT_VALID);
            }
        }
        query
                .eq(Objects.nonNull(req.getAssetId()), TblAssetAccount::getAssetId, req.getAssetId())
                .eq(Objects.nonNull(req.getAppUserId()), TblAssetAccount::getOwnerId, req.getAppUserId())


                .orderByDesc(TblAssetAccount::getCreateTime);
        Page<AssetAccountVo> assetAccountVoPage = assetAccountMapper.selectJoinPage(new Page<>(req.getCurrent(), req.getPageSize()), AssetAccountVo.class, query);
        assetAccountVoPage.setRecords(assetAccountVoPage.getRecords().stream().peek(x->{
           try {
              x.setPhone(MyAESUtil.decrypt(x.getPhone()));
           } catch (Exception e) {
             //  throw new RuntimeException(e);
           }
       }).toList());
       return assetAccountVoPage;
    }


    public Boolean setState(Long id, Integer state) {
        LambdaUpdateChainWrapper<TblAssetAccount> updateChainWrapper = new LambdaUpdateChainWrapper<>(baseMapper);
        updateChainWrapper.eq(TblAssetAccount::getId, id)
                .set(TblAssetAccount::getState, state);
        return updateChainWrapper.update();
    }


    public Page<AssetTransationRecordVo> getRecordList(AssetAccountRecordReqest req) {
        MPJLambdaWrapper<TblAssetTransactionRecord> query = JoinWrappers.lambda(TblAssetTransactionRecord.class)
                .leftJoin(TblAssetAccount.class, TblAssetAccount::getAccountNo, TblAssetAccount::getAccountNo)
                .leftJoin(TblAsset.class, TblAsset::getId, TblAssetAccount::getAssetId)
                .selectAll(TblAssetTransactionRecord.class)
                .select(TblAssetAccount::getAssetId, TblAssetAccount::getOwnerId)
                .select(TblAsset::getAssetName);
        query.eq(Objects.nonNull(req.getAssetId()), TblAssetAccount::getAssetId, req.getAssetId())
                .eq(Objects.nonNull(req.getAccountNo()), TblAssetAccount::getAccountNo, req.getAccountNo())
                .eq(Objects.nonNull(req.getAppUserId()), TblAssetAccount::getOwnerId, req.getAppUserId())
                .eq(TblAssetAccount::getReferProtocol, 1155)
                .orderByDesc(TblAssetTransactionRecord::getCreateTime);

        if(StringUtils.isNotBlank(req.getStartTime())) {
            try {
                Long start = ToolsUtil.parseDate(req.getStartTime());
                query.gt(TblAssetTransactionRecord::getCreateTime, start);
            } catch (Exception e) {
                throw new ChainException(ErrorMessage.ARGUMENT_NOT_VALID);
            }
        }
        if(StringUtils.isNotBlank(req.getEndTime())) {
            try {
                Long end = ToolsUtil.parseDate(req.getEndTime());
                query.gt(TblAssetTransactionRecord::getCreateTime, end);
            } catch (Exception  e) {
                throw new ChainException(ErrorMessage.ARGUMENT_NOT_VALID);
            }
        }
        return   assetTransactionRecordMapper.selectJoinPage(new Page<>(req.getCurrent(), req.getPageSize()), AssetTransationRecordVo.class, query);
    }
}
